package com.max.xihu.netty.nio.niochat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author: Max
 * @Date: 2020-03-23 22:23
 * @Description:
 */
public class ChatServer {

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private static final int PORT = 6667;


    public ChatServer(){
        try {
            //获取选择器
            selector = Selector.open();

            //获取ServerSocketChannel
            serverSocketChannel = ServerSocketChannel.open();

            //绑定端口
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));

            //设置非阻塞
            serverSocketChannel.configureBlocking(false);

            //注册serverSocketChannel到selector
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    public void listen(){
        try {
            while (true){
                int count = selector.select();
                if (count > 0){//有事件处理
                    //遍历得到selectionKey集合
                    Iterator<SelectionKey> iterator = selector.keys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        //监听accept
                        if (key.isAcceptable()){
                            SocketChannel accept = serverSocketChannel.accept();
                            accept.configureBlocking(false);
                            accept.register(selector,SelectionKey.OP_READ);
                            System.out.println(accept.getRemoteAddress()+" 上线了");
                        }
                        //通道可读
                        if (key.isReadable()){
                            readMsg(key);
                        }
                    }
                }else{
                    System.out.println("等待......");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

    private void readMsg(SelectionKey key){

        SocketChannel channel = null;

        try {

            channel = (SocketChannel)key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);

            if (count > 0){
                String str = new String(buffer.array());
                System.out.println("from 客户端："+str);

                //向其他客户端转发消息
                sendMsgToOther(str,channel);
            }

        }catch (IOException e){
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了");
                key.cancel();
                channel.close();
            }catch (IOException e1){
                e1.printStackTrace();
            }


        }
    }

    private void sendMsgToOther(String msg, SocketChannel selfChannel) throws IOException {

        System.out.println("服务器转发消息中");

        for (SelectionKey key : selector.keys()){

            Channel targetChannel = key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel != selfChannel){

                SocketChannel dest = (SocketChannel) targetChannel;

                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(buffer);
            }

        }
    }



    public static void main(String[] args) {
        ChatServer server = new ChatServer();
        server.listen();
    }
}
